/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package botobjects;

import interfaces.BotObject;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import org.apache.log4j.Logger;
import org.jibble.pircbot.Colors;

import tools.StringTools;
import database.DBConnectionFactory;

/**
 * Represents an aid request
 * 
 * 
 */
public class Aid implements BotObject, Comparable<Aid> {
   /**
    * Removes the specified aid request
    * 
    * @param args
    *           Specifies the name of the province that made the aid request and the type of resource to remove the request for
    * @return true if the aid request was deleted successfully
    */
   public static boolean deleteFromDB(final String... args) {
	  boolean out = false;
	  if (args.length < 2)
		 return out;
	  PreparedStatement ps = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("DELETE FROM aid WHERE name = ? AND resource = ?");
		 ps.setString(1, args[0]);
		 ps.setString(2, args[1]);
		 if (ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Returns a list of all active aid requests
    * 
    * @return a List of Aid objects
    */
   public static List<Aid> getAidList() {
	  List<Aid> out = new LinkedList<Aid>();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM aid ORDER BY requesttime DESC");
		 rs = ps.executeQuery();
		 while (rs.next()) {
			out.add(new Aid(rs.getString("name"), rs.getString("resource"), rs.getInt("amount"), rs.getTimestamp("requesttime")
				  .getTime(), rs.getString("urgency")));
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   private String provname = "";
   private String resource = "";
   private int amount = 0;

   private Long requesttime = 0L;

   private String urgency = "";

   public Aid(final String provname, final String resource, final int amount, final Long requesttime, final String urgency) {
	  this.provname = provname;
	  this.resource = resource;
	  this.amount = amount;
	  this.requesttime = requesttime;
	  this.urgency = urgency;
   }

   /**
    * Compares aid requests based on the age of the request
    */
   @Override
   public int compareTo(final Aid o) {
	  if (requesttime < o.getRequestTime())
		 return -1;
	  else if (equals(o))
		 return 0;
	  else
		 return 1;
   }

   /**
    * Aid requests are considered equal if they were added at exactly the same time, seeing as the purpose for comparing them is
    * just to put them in order of age
    */
   @Override
   public boolean equals(final Object o) {
	  if (o == null)
		 return false;
	  if (o instanceof Aid)
		 return getRequestTime().equals(((Aid) o).getRequestTime());
	  return false;
   }

   public int getAmount() {
	  return amount;
   }

   @Override
   public List<String> getIRCOutput(final int outputType, final String... args) {
	  List<String> out = new LinkedList<String>();
	  if (args.length < 2 || StringTools.isNullOrEmpty(getProvname()) || StringTools.isNullOrEmpty(getResource())
			|| getRequestTime() == null || getUrgency() == null)
		 return out;
	  String pattern = "EEE, MMM d, H:mm:ss";
	  SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.US);
	  final NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
	  nf.setGroupingUsed(true);

	  TimeZone tz = TimeZone.getTimeZone("GMT" + args[0]);
	  sdf.setTimeZone(tz);

	  out.add(Colors.BLUE + args[1] + ": " + Colors.RED + getProvname() + Colors.OLIVE + " needs " + Colors.TEAL
			+ nf.format(getAmount()) + " " + getResource() + Colors.BLUE + ". Added: " + sdf.format(new Date(getRequestTime()))
			+ " " + getUrgency());
	  return out;
   }

   public String getProvname() {
	  return provname;
   }

   public Long getRequestTime() {
	  return requesttime;
   }

   public String getResource() {
	  return resource;
   }

   @Override
   public Map<String, Object> getRPCOutput(final int... includes) {
	  Map<String, Object> out = new HashMap<String, Object>();
	  if (StringTools.isNullOrEmpty(getProvname()) || StringTools.isNullOrEmpty(getResource()) || getRequestTime() == null
			|| getUrgency() == null)
		 return out;
	  out.put("Province", getProvname());
	  out.put("Resource", getResource());
	  out.put("Amount", getAmount());
	  out.put("Urgency", getUrgency());
	  out.put("Request Time", new Date(getRequestTime()));
	  return out;
   }

   public String getUrgency() {
	  return urgency;
   }

   @Override
   public int hashCode() {
	  assert false : "hashCode not designed";
	  return 42; // any arbitrary constant will do
   }

   @Override
   public boolean saveToDB() {
	  boolean out = false;
	  if (StringTools.isNullOrEmpty(getProvname()) || StringTools.isNullOrEmpty(getResource()) || getRequestTime() == null
			|| getUrgency() == null)
		 return out;
	  PreparedStatement ps = null;
	  try {
		 deleteFromDB(getProvname(), getResource());

		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("INSERT INTO aid VALUES(?,?,?,?,?)");
		 ps.setString(1, getProvname());
		 ps.setString(2, getResource());
		 ps.setInt(3, getAmount());
		 ps.setTimestamp(4, new Timestamp(getRequestTime()));
		 ps.setString(5, getUrgency());
		 if (ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   public void setAmount(final int amount) {
	  this.amount = amount;
   }
}
